import moment from "moment";
import * as ddscode from "dingtalk-jsapi";
let app = getApp();
Page({
  data: {
    fileTypeList:[
      {name:'甲方'}, 
      {name:'乙方'}, 
    ],
    clearValue: '我是默认文本',
    autoClearValue: '带有清空功能',
    date:'',
    checked: true,
    defaultChecked: false,
    checked2: true,
    isReimbursement:false,  //是否显示报销下面的内容
    StatusOptions: [{
      value: 0,
      name: '刘总'
    },
    {
      value: 1,
      name: '徐总'
    },
    {
      value: 2,
      name: '马总'
    },
    {
      value: 3,
      name: '其他'
    }],
    statusindex: '',
    switch1: true,  //是否报销的选框按钮

    StatusOptionskh: [{
      value: 0,
      namekh: '77'
    },
    {
      value: 1,
      namekh: '88'
    }],


    // 表单数据
    getga:{
      fid:'',
      conde:"", //项目编码
      date:'', //日期
      text:'', // 日志
      isBao:false, // 是否包厢
      sqr:'', // 申请人
      jinen:0 , //金额
      baolix:'',//类型
      zhaitext:'', // 申请摘要
      poinssa:'', //地理位置
      place:'', //办公地点
      img:'',  // 图片
      imgcode:'',  // 图片
      startdate:'', // 开始日期
      enddate:'', // 结束日期
    },

    isCalendar:false,

    
    
  },

  // onHide() {
  //   // 页面隐藏
  //   console.log("111")
  // },
  onUnload() {
    // 页面被关闭
    var that = this;
    
  },

  onLoad(query) {
    var that = this;
    console.log("页面携带数据==>",query)
    var getga = that.data.getga;
    getga['date']  = "";
    getga['fid'] = '',
    getga['date'] = '',
    getga['text'] = '',
    getga['isBao'] = false,
    getga['sqr'] = '',
    getga['jinen'] = '0',
    getga['baolix'] = '',
    getga['zhaitext'] = '',
    getga['poinssa'] = '',
    getga['place'] = '',
    getga['img'] = '',
    getga['imgcode'] = '',
    getga['startdate'] = '',
    getga['enddate'] = '',
    that.setData({
      getga,
    })

    var date = new Date();
    var getga = that.data.getga;
    getga['date']  = date.getFullYear()+'-'+ ((date.getMonth()+1)<10?'0'+(date.getMonth()+1):(date.getMonth()+1))  +'-'+(date.getDate()<10?'0'+date.getDate():date.getDate());
    that.setData({
      getga,
    })

    if(query.fid){
      var get = that.data.getga;  //数据
      get['fid'] = query.fid;
      that.setData({
        getga:get
      })
    }

    return
    if(query.item){
     var get = that.data.getga;
     var item = JSON.parse(query.item)
     item['报销截图'] = item.报销截图.replace(/\|/g, "&");
     get['fid'] = item['单据内码']
     get['conde'] = item['行ID']
     get['text'] = item['工作日志']
     get['isBao'] = item['是否报销'] != 0?true:false
     get['jinen'] = item['报销金额']
     get['zhaitext']= item['报销摘要']
     get['poinssa']= item['定位']
     get['place']= item['办公地点']
     get['baolix']= item['费用项目']
     get['startdate']= item['开始日期']
     get['enddate']= item['结束日期']
     get['img']= item['报销截图']
     
      that.setData({
        getga:get,
        isReimbursement:item['是否报销']!= 0?true:false
      })
    }
 },


 //获取开始时间
  onTtartData(e){ 
  var that = this;
        var startData = that.data.getga.startdate;
      my.datePicker({
        currentDate: startData,
        success: (res) => {
          var getga = that.data.getga
          getga.startdate = res.date
          that.setData({
            getga:getga
          })
        },
      });
        
   },
//获取结束时间
 onEndData(e){ 
          var that = this;
        var enddate = that.data.getga.enddate;
        my.datePicker({
          currentDate: enddate,
          success: (res) => {
            var getga = that.data.getga
            getga.enddate = res.date
            that.setData({
              getga:getga
            })
          },
        });

     },
 
  //时间选择器
  datePicker(e) {
    var { pid, index } = e.target.dataset.parent;
    let current = moment().format("YYYY-MM-DD HH:mm:ss");
    var moment_that = moment;
    dd.datePicker({
      format: "yyyy-MM-ss",
      currentDate: current,
      success: res => {
        let date = res.date;
        if (date.length == 16) {
          var moment = moment_that(date, "YYYY-MM-DD HH:mm");
          date = moment.format("YYYY-MM-DD HH:mm:ss");
        }
        //赋值给控件绑定显示
        var getga = this.data.getga;
        getga['date'] = date;
       
        this.setData({
          getga
        })

        console.log("选中的日期", date);
      }
    });
  },

  //选择地图点
  getplace(res){
    var that  = this;
    ddscode.biz.map.locate({
      scope: 500, // 限制搜索POI的范围；设备位置为中心，scope为搜索半径
      onSuccess: function (result) {
          /* result 结构 */
        console.log('result',result)
        // that.setData({
        //   place_data:result,
        //   place_name:result.title,
        // })
        var getga = that.data.getga
        getga.poinssa = result['province']+result['city']+result['adName']+result['snippet']+result['title']
        that.setData({
          getga:getga
        })

        console.log('that.data.getga',that.data.getga)
      },
      onFail: function (err) {
        app.hintPop(err.errorMessage,'fail');
      }
  });
  },


 switch2Change(e){
  var that = this;
  console.log('是否报销', e.detail.value);
  var getga = that.data.getga
    
  if(e.detail.value == true){
    getga['isBao'] = true
    that.setData({
      isReimbursement : true,
      getga
    })
  }else{
    getga['isBao'] = false
    that.setData({
      isReimbursement : false,
      getga
    })
  }
},



 //报销类型的状态下拉框 状态改变可以拿到下标 赋值 还可以根据下标知道选中的是哪个值 
 statusChange(e) {
   
   var that = this;
   var StatusOptions = that.data.StatusOptions;
   var getga = that.data.getga
  getga['baolix'] = StatusOptions[e.detail.value].name;
  console.log("报销类型==》",StatusOptions[e.detail.value].name)
  that.setData({
    statusindex: e.detail.value,
    status: e.detail.value,
    getga:getga
  })
},



onOneChange(e) {
  console.log('checkbox发生change事件，携带value值为：', e)
  var wuliaoList = this.data.wuliaoList;
  var index = e.currentTarget.dataset.index
  wuliaoList[index]['selected'] = !wuliaoList[index]['selected'] 
  this.setData({
    wuliaoList
  })
},

// 提交按钮的
onPrimLargeTap(e) {
  var that = this;
  // console.log("点击了提交按钮that.data.getga", that.data.getga);
  // return
  var  {
    fid,
    conde, //行id
    date, //日期
    text, // 日志
    isBao, // 是否包厢
    sqr, // 申请人
    jinen, //金额
    baolix,//类型
    zhaitext, // 申请摘要
    poinssa, //定位
    place , // 
    img,
    imgcode,
    startdate, // 开始日期
    enddate, // 结束日期
    
  } = that.data.getga

  if(startdate == ''){
    dd.showToast({
      type: 'fail',
      content:'未选择日期',
      duration: 2000,
    });
    return
  }
  if(enddate == ''){
    dd.showToast({
      type: 'fail',
      content:'未选择日期',
      duration: 2000,
    });
    return
  }
  // if(poinssa == ''){
  //   dd.showToast({
  //     type: 'fail',
  //     content:'未定位',
  //     duration: 2000,
  //   });
  //   return
  // }
  var time1 = new Date(startdate);
  var time2 = new Date(enddate);

  // 比较两个时间
  if (time1 > time2) {
    dd.showToast({
      type: 'fail',
      content:'结束时间不能小于开始时间',
      duration: 2000,
    });
    return
  } 

  if(text == ''){
    dd.showToast({
      type: 'fail',
      content:'未填写日志',
      duration: 2000,
    });
    return
  }

  
  if(isBao){
    if(that.data.getga.jinen == ''){
      dd.showToast({
        type: 'fail',
        content:'申请金额未填写',
        duration: 2000,
      });
      return
    }
    if(baolix == ''){
      dd.showToast({
        type: 'fail',
        content:'报销类型未选择',
        duration: 2000,
      });
      return
    }
  }
  var data = JSON.stringify(
    {
      "fid": fid, 
      "F_ZYKJ_Base_lpe": app.globaldata.user['员工工号'],  //员工工号
      "F_UNW_Text_apv": place,  // 办公地点
      "F_ZYKJ_Date_w24": '',  // 日期
      "F_ZYKJ_CheckBox_gy7": isBao, //是否报销
      "F_ZYKJ_Amount_0ub": parseFloat(jinen), // 报销金额
      "F_ZYKJ_Base_ijl": baolix || '0', // 费用项目  
      "F_ZYKJ_Remarks_xni": text, // 工作日志
      "FEntryID": conde,  // 行id
      "F_ZYKJ_Text_2fp": zhaitext , // 申请摘要
      "F_UNW_Text_tzk": poinssa  , // 定位位置
      "F_ZYKJ_Picture_j40": imgcode, // 图片上传 
      "F_UNW_Datetime3": startdate,
      "F_UNW_Datetime4": enddate
    }
  )

  dd.showLoading({ 
    content: '保存中...'
  });

  dd.httpRequest({
    url: 'http://openapi.keyboardadmin.com:10010/xg_project',
    method: 'POST',
    data: data,
    dataType: 'json',
    success: function (res) {
      console.log('获取我的项目列表数据成功==>', res)
      if (res.data.data.code == 200) {

        dd.alert({
          title: '提示',
          content: '您已保存成功',
          buttonText: '我知道了',
          success: () => {
            dd.navigateBack({
              delta: 1
            })
          },
        });
        
      } else {
        dd.showToast({
          type: 'fail',
          content: res.data.data.title,
          duration: 2000,
        });
      }
    },
    fail: function (res) {
      // dd.alert({ content: 'fail' });
    },
    complete: function (res) {
      dd.hideLoading()
    }
  });
},

//上传图片
upHide(){
  var that = this;


  dd.chooseImage({
    //请求图片
    count: 1, //上传图片张数限制
    success: res => {
      console.log("返回的文件信息为:");
  
      console.log(res);
      
      
      var filePath = res.filePaths[0];
      var getga = that.data.getga
                getga.img = filePath
                that.setData({
                  getga:getga,

                })
        that.imgCompression(filePath, 0.4).then(function (imasss) {
          console.log("压缩后的图片", imasss);
          var token = "D1SA2__@D12532DWA1D2d@w2a1d223"
          var url = "http://openapi.keyboardadmin.com:10010/update_picture?token="+token
          dd.uploadFile({
            url:url,
            fileType: 'image',
            fileName: 'picture',
            filePath: imasss, 
            formData:{},
            success: res => {
              console.log(res.data);
              var r = JSON.parse(res.data);
              if(r.code == 200){
                console.log('filePath==>',filePath);
                var getga = that.data.getga
                getga.img = filePath
                getga.imgcode = r.data.Result.FileId
                that.setData({
                  getga:getga,
                  isimg:true

                })

              }else{
                dd.showToast({
                  title: r.data,
                  type: "fail"
                });
              }
              
            },
            fail: function(res) { 
              dd.showToast({
                title: "上传图片信息失败",
                type: "fail"
              });
            }
          })
          
        }).catch(function (error) {
          console.error(error);
        });
    }
  });
  
  
  
},


 /**
     * 
     * @param {图片链接} img 
     * @param {压缩后大小} amount 
     */
    imgCompression(img, amount) {
      var that = this;
      dd.showLoading({
        content: '图片正在压缩中...'
      });
      return new Promise(function (resolve, reject) {
        console.log("img==>",img)
        dd.getFileInfo({  
          apFilePath: img,
          success: function success(info) {
            console.log("info.size==>", info.size);
            console.log("info.size==>", amount * 1000 * 1000);
            if (info.size < amount * 1000 * 1000) {
              dd.hideLoading();
              resolve(img);
              return img;
            } else {
              dd.getImageInfo({
                src: img,
                // 图片路径
                success: function success(res) {
                  var height = res.height;
                  var width = res.width;
                  console.log('width', width);
                  console.log('height', height);
                  var k = parseInt(res.width * 0.8);
                  var g = parseInt(res.height * 0.8);
                  that.setData({
                    width:k,
                    height:g,
                  })
                  var canvas = my.createCanvasContext('canvas');
                  console.log("canvas==>",canvas);
                  canvas.drawImage(img, 0, 0, k, g);
                  console.log("canvas==>",canvas);
                  canvas.draw(true);
                  setTimeout(() => {
                    canvas.toTempFilePath({
                      x: 0,
                      y: 0,
                      width: width,
                      height: height,
                      destWidth: k,
                      destHeight: g,
                      success(res) {
                        console.log('图片2', res.filePath);
                        that.imgCompression(res.filePath, amount).then(function (data) {
                          resolve(data);
                        }).catch(function (error) {
                          dd.hideLoading();
                          reject(error);
                          console.error(error);
                        });
                      }
                    })
                  },1000);
                }
              });
            }
          },
          fail: function fail(err) {
            dd.hideLoading();
            reject(err);
          }
        });
      });
    },


  onTap(e) {
    console.log('onTap', e)
    
  },
  onInput(e) {
    // 异步返回错误示例
    setTimeout(()=>{
      this.setData({
        error: 'error 222'
      })
    }, 3000);
    console.log('onInput', e.detail.value)
  },

// 获取编码的内容
  onInputbm(e){
    var that = this;
    var getga = that.data.getga
    getga.conde = e.detail.value
    this.setData({
      getga:getga
    })
  },

  // 获取报销金额的内容
  onInputbm3(e){
    var that = this;
    var getga = that.data.getga
    getga.jinen = e.detail.value
    this.setData({
      getga:getga
    })
  },

  // 办公地点
  getSelectFileTypeList(e){
    var that = this;
    var getga = that.data.getga
    getga.place = e.name
    this.setData({
      getga:getga
    })
  },


  // 获取工作日志的内容
  obtainRemarks(e){
    var that = this;
    var getga = that.data.getga
    getga.text = e.detail.value
    this.setData({
      getga:getga
    })
  }, 
  // 获取申请摘要
  obtainZhaitext(e){
    var that = this;
    var getga = that.data.getga
    getga.zhaitext = e.detail.value
    this.setData({
      getga:getga
    })
  }, 
  


  //前往日历选择
  toCalendar(){
    dd.navigateTo({ 
      url: '/pages/calendar/calendar',  
    })
  },

  ondawddw(){
    this.setData({
      isCalendar:!this.data.isCalendar
    })
  },
  onChoose(e){
    console.log("99999999",e)
    this.setData({
      get_Date:e[0]
    })
  },

});
